<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者身份证" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者身份证"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主治医生" prop="doctorId">
        <el-select v-model="queryParams.doctorId" placeholder="请选择主治医生" clearable>
          <el-option
            v-for="dict in dict.type.fee_guahao_doctor"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="就诊科室" prop="departmentId">
        <el-select v-model="queryParams.departmentId" placeholder="请选择就诊科室" clearable>
          <el-option
            v-for="dict in dict.type.hs_department"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="就诊日期" prop="visitDate">
        <el-date-picker clearable
          v-model="queryParams.visitDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择就诊日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="复诊日期" prop="followUpDate">
        <el-date-picker clearable
          v-model="queryParams.followUpDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择复诊日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['visit:visitRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['visit:visitRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['visit:visitRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['visit:visitRecord:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="single"
          @click="handleCheckAdd"
          v-hasPermi="['visit:visitRecord:addCheck']"
        >创建检查订单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="single"
          @click="handlePrescriptionAdd"
          v-hasPermi="['visit:visitRecord:addPrescription']"
        >创建处方表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="visitRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="就诊单号" align="center" prop="visitId" />
      <el-table-column label="患者身份证" align="center" prop="patientId" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="主治医生" align="center" prop="doctorId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fee_guahao_doctor" :value="scope.row.doctorId"/>
        </template>
      </el-table-column>
      <el-table-column label="就诊科室" align="center" prop="departmentId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hs_department" :value="scope.row.departmentId"/>
        </template>
      </el-table-column>
      <el-table-column label="症状描述" align="center" prop="symptoms" />
      <el-table-column label="诊断结果" align="center" prop="diagnosis" />
      <el-table-column label="其他备注" align="center" prop="visitNotes" />
      <el-table-column label="就诊日期" align="center" prop="visitDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.visitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="复诊日期" align="center" prop="followUpDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.followUpDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['visit:visitRecord:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['visit:visitRecord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改就诊信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者身份证" prop="patientId">
          <el-input v-model="form.patientId" placeholder="请输入患者身份证" />
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="主治医生" prop="doctorId">
          <el-select v-model="form.doctorId" placeholder="请选择主治医生">
            <el-option
              v-for="dict in dict.type.fee_guahao_doctor"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊科室" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择就诊科室">
            <el-option
              v-for="dict in dict.type.hs_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="症状描述" prop="symptoms">
          <el-input v-model="form.symptoms" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="诊断结果" prop="diagnosis">
          <el-input v-model="form.diagnosis" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="其他备注" prop="visitNotes">
          <el-input v-model="form.visitNotes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="就诊日期" prop="visitDate">
          <el-date-picker clearable
            v-model="form.visitDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择就诊日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="复诊日期" prop="followUpDate">
          <el-date-picker clearable
            v-model="form.followUpDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择复诊日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--添加检查表对话框-->
    <el-dialog :title="title" :visible.sync="checkOpen" width="500px" append-to-body>
      <el-form ref="checkForm" :model="checkForm" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="就诊单号" prop="cVisitId">
          <el-input v-model="checkForm.cVisitId" placeholder="就诊单号就诊单号" readonly :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="checkForm.patientName" placeholder="患者姓名" readonly :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="检查项目" prop="checkItem">
          <el-select v-model="checkForm.checkItem" placeholder="请选择需要检查的项目">
            <el-option
              v-for="dict in dict.type.fee_jiancha_xiangmu"
              :key="dict.value"
              :label="dict.label"
              :value="dict.label"
              @click.native="changePrice(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="price">
          <el-input :disabled="true" v-model="price"  />
        </el-form-item>
<!--        <el-form-item label="检查结果" prop="checkNotes">-->
<!--          <el-input v-model="checkForm.checkNotes" type="textarea" placeholder="请输入备注"-->
<!--                    :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCheckForm">确 定</el-button>
        <el-button @click="cancelCheckForm">取 消</el-button>
      </div>
    </el-dialog>

    <!--添加处方表-->
    <el-dialog :title="title" :visible.sync="prescriptionOpen" width="500px" append-to-body>
      <el-form ref="prescriptionForm" :model="prescriptionForm" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="就诊单号" prop="pVisitId">
          <el-input v-model="prescriptionForm.pVisitId" placeholder="请输入就诊单号" :maxlength="11" readonly
                    :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="prescriptionForm.patientName" placeholder="请输入患者姓名" readonly clearable
                    :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="药品列表" prop="drugName">
          <el-select v-model="prescriptionForm.drugName" placeholder="请选择药品" clearable :style="{width: '100%'} " @change="calculateDrugPrice">
            <el-option v-for="(item, index) in drugNameList" :key="index" :label="item.label"
                       :value="item.label" :disabled="item.disabled" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计数器" prop="drugCount">
          <el-input-number v-model="prescriptionForm.drugCount" placeholder="计数器" :min="1" :max="99" @change="calculateDrugPrice"></el-input-number>
        </el-form-item>
        <el-form-item label="金额" prop="price">
          <el-input :disabled="true" v-model="price"  />
        </el-form-item>
        <el-form-item label="备注" prop="checkNote">
          <el-input v-model="prescriptionForm.checkNotes
        " type="textarea" placeholder="请输入备注"
                    :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPrescriptionForm">确 定</el-button>
        <el-button @click="cancelPrescriptionForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listVisitRecord, getVisitRecord, delVisitRecord, addVisitRecord, updateVisitRecord, addCheckOrder,addDrugRequest,listDrugName } from "@/api/visit/visitRecord";
import { addPrescriptionlist} from "@/api/visit/prescriptionlist"
import {forEach} from "core-js/stable/dom-collections";
import {addChecklist} from "@/api/visit/checklist";
export default {
  name: "VisitRecord",
  dicts: ['hs_department', 'fee_guahao_doctor','fee_jiancha_xiangmu'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 就诊信息表格数据
      visitRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      checkOpen:false,
      prescriptionOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientId: null,
        patientName: null,
        doctorId: null,
        departmentId: null,
        symptoms: null,
        diagnosis: null,
        visitNotes: null,
        visitDate: null,
        followUpDate: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      checkForm:{
        price:0,
        isChecked:"未支付"
      },
      prescriptionForm:{},
      drugNameList:{},
      //字典
      price:0,
      // 表单校验
      rules: {
        patientId: [
          { required: true, message: "患者身份证不能为空", trigger: "blur" }
        ],
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" }
        ],
        doctorId: [
          { required: true, message: "主治医生不能为空", trigger: "blur" }
        ],

        checkItem: [
          { required: true, message: '请输入需要检查的项目', trigger: 'change'}
        ],
        drugName: [{
          required: true,
          message: '请选择药品',
          trigger: 'change'
        }],
      },

    };
  },
  created() {
    this.getList();
    this.getDicts("fee_jiancha_xiangmu").then(response => {
      this.checkitems = response.data;
      console.log(this.checkitems);
    });
    this.getDrugNames();

  },
  methods: {
    /** 查询就诊信息列表 */
    getList() {
      this.loading = true;
      listVisitRecord(this.queryParams).then(response => {
        this.visitRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    getDrugNames(){
      listDrugName().then(response =>{
        this.drugList = response.rows;
        var names = []
        var i = 0;
        this.drugList.forEach(function (drug){
          names.push({label:drug.drugName,value: drug.price })
          i++;
        })
        this.drugNameList = names;
        console.log(this.drugNameList);
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        visitId: null,
        patientId: null,
        patientName: null,
        doctorId: null,
        departmentId: null,
        symptoms: null,
        diagnosis: null,
        visitNotes: null,
        visitDate: null,
        followUpDate: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.visitId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加就诊信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const visitId = row.visitId || this.ids
      getVisitRecord(visitId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改就诊信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.visitId != null) {
            updateVisitRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVisitRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const visitIds = row.visitId || this.ids;
      this.$modal.confirm('是否确认删除就诊信息编号为"' + visitIds + '"的数据项？').then(function() {
        return delVisitRecord(visitIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        this.$modal.msgError("该患者有关联信息，无法删除")
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('visit/visitRecord/export', {
        ...this.queryParams
      }, `visitRecord_${new Date().getTime()}.xlsx`)
    },
    /**创建检查订单操作**/
    handleCheckAdd(){
      this.resetCheckForm();
      this.reset();
      const visitId = this.ids;
      getVisitRecord(visitId).then(response => {
        this.form = response.data;
        this.checkForm.patientName = this.form.patientName;
        this.checkForm.cVisitId = this.form.visitId;
        this.checkForm.isChecked = "未支付";
        this.checkForm.price = 0
        // console.log(this.checkForm.patient_name);
        // console.log(this.form.patientName);
        this.checkOpen = true;
        this.title = "添加检查订单";
      });
    },
    resetCheckForm(){
      this.checkForm = {
        cVisitId: null,
        patientName: null,
        checkNotes: null,
        checkItem: null,
        isChecked: "未支付"
      }
    },
    submitCheckForm(){

      this.checkForm.price = this.price
      console.log(this.checkForm);
      if (this.checkForm.checkItem != null ) {
        addCheckOrder(this.checkForm).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.checkOpen = false;

        });
      }
      this.price = 0
    },
    cancelCheckForm(){
      this.checkOpen = false;
      this.resetCheckForm();
    },

    /**创建处方表操作**/
    handlePrescriptionAdd(){
      this.resetPrescriptionForm();
      this.reset();
      const visitId = this.ids;
      getVisitRecord(visitId).then(response => {
        this.form = response.data;
        this.prescriptionForm.patientName = this.form.patientName;
        this.prescriptionForm.pVisitId = this.form.visitId;
        this.prescriptionOpen = true;
        this.title = "添加处方";
      });
    },

    submitPrescriptionForm(){
      if (this.prescriptionForm.drugName != null && this.prescriptionForm.drugCount > 0) {
        // addDrugRequest(this.prescriptionForm).then(response =>{
        //   console.log(this.prescriptionForm)
        // })

        this.prescriptionForm.drugPrice = this.price;
        console.log(this.prescriptionForm)
        addPrescriptionlist(this.prescriptionForm).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.prescriptionOpen = false;
        })
      }
    },
    cancelPrescriptionForm(){
      this.prescriptionOpen = false;
      this.resetPrescriptionForm();
    },
    resetPrescriptionForm(){
      this.prescriptionForm = {
        pVisitId: null,
        patientName: null,
        drugName: null,
        drugCount: null,
        drugPrice: null,
        checkNote: null,
        drugStatus: "未支付"
      }
    },
    changePrice(e){
      console.log(this.checkForm)
      this.price = e
    },
    calculateDrugPrice(){
      // console.log(this.prescriptionForm);
      // console.log("---------------------------")
       if(this.prescriptionForm.drugName != null){
         var p = 0;
         var name = this.prescriptionForm.drugName
         this.drugNameList.forEach(function (drug){
           if(drug.label === name){
             p = drug.value;
           }
         })

         this.price = p * this.prescriptionForm.drugCount;

       }
    }

  }
};
</script>
